The next data type we will explore from Python Data Types is Python Dictionaries (type dict).
Python dictionaries are an unordered collection of data in a Key-Value pair wrapped in curly brackets { }
. You can not slice or index from a dictionary as it is an unordered data collection. If you want to retrieve data from a dictionary, you can pull it by its key.
A common question with dictionaries is why you would use these vs. a list. The easiest way to choose is to look at them side by side.
Dictionaries:
- An unordered collection of data
- Retrieve data by key
Lists:
- An ordered sequence of objects that can be indexed or sliced
- Objects are retrieved by index number
As you start in programming, the hardest thing is knowing what you have to use in situations like this. As time passes, you will get more comfortable with programming, and what you can do with the different data types becomes easier.
A basic dictionary would look like this:
my_dict = {'k1': 'Value1', 'K2': 'Value2', 'K3':'Value3'}
To retrieve a value whose key is associated with K2:
my_dict['K2']
This would return:'Value2'
If you want to add to a dictionary:
my_dict['K4'] = 'value4'
If we wanted to retrieve K4
my_dict[‘K4”]
‘value4’
Looking at how the dictionary looks
{‘k1’: ‘Value1’, ‘K2’: ‘Value2’, ‘K3’: ‘Value3’, ‘K4’: ‘value4’}
my_dict
We have an issue with K4; if we want to change it, it is the same process as we took to add K4.
my_dict['K4'] = 'Value4'
When we look at K4 now:
my_dict['K4']
'Value4'
my_dict
{'k1': 'Value1', 'K2': 'Value2', 'K3': 'Value3', 'K4': 'Value4'}
If you wanted to see the data type of the value associated with a key and run methods specific to that data type:
type(my_dict['K4'])
<class 'str'>
my_dict['K4'].upper()
'VALUE4'
my_dict['K4'].lower()
'value4'
my_dict['K4'].split('l')
['Va', 'ue4']
Dictionaries have methods like the other data types. Dictionary methods are located here: Dictionary Methods. There are not as many to start with, and there are only about 3 you will use 80% of the time.
.keys()
- Keys will return all the keys in the dictionary.
my_dict.keys()
dict_keys(['k1', 'K2', 'K3', 'K4', 'K5'])
- Keys will return all the keys in the dictionary.
.values()
- Values will return all the values in the dictionary
my_dict.values()
dict_values(['Value1', 'Value2', 'Value3', 'Value4', 100])
- Values will return all the values in the dictionary
.items()
- Items will return the KvP, and each KvP is in a tuple
my_dict.items()
dict_items([('k1', 'Value1'), ('K2', 'Value2'), ('K3', 'Value3'), ('K4', 'Value4'), ('K5', 100)])
- Items will return the KvP, and each KvP is in a tuple